package com.acme.superchat.service.server;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Gregory Sobko
 */
public class ClientOutputBuffer implements Runnable {
    private PrintWriter out;
    private List<String> queue;
    private Lock printLock = new ReentrantLock();
    private Condition somethingWasPrinted = printLock.newCondition();
    public ClientOutputBuffer(PrintWriter out) {
        this.out = out;
        queue = new ArrayList<>();
    }

    @Override
    public void run() {
        while (true) {
            try{
                printLock.lock();
                while (queue.isEmpty()){
                    somethingWasPrinted.await();
                }
                out.println(queue.remove(0));
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } finally {
                printLock.unlock();
            }

        }
    }
    public void print(String printString) {
        try{
            printLock.lock();
            queue.add(printString);
            somethingWasPrinted.signalAll();
        }finally {
            printLock.unlock();
        }
    }
    public void printList(List<String> list) {
        try{
            printLock.lock();
            for(String stringLine: list) {
                queue.add(stringLine);
            }
            somethingWasPrinted.signalAll();
        }finally {
            printLock.unlock();
        }
    }

}
